package com.ng.sys.service.impl;

import java.util.LinkedList;
import java.util.List;

import org.springframework.stereotype.Service;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.ng.sys.model.domain.*;
import com.ng.sys.service.IRole;

@Service
public class RoleImpl implements IRole {

	@Override
	public boolean delete(String id) {
		Db.delete("delete from "+RoleMenu.TABLE_NAME+" where role_id=?",id);
		Db.delete("delete from "+UserRole.TABLE_NAME+" where role_id=?",id);
		Db.delete("delete from "+Role.TABLE_NAME+" where id=?",id);
        return true;
	}

	@Override
	public List<String> getRoleMenuIds(String roleId) {
		List<RoleMenu> roleMenus=RoleMenu.dao.find("select menu_id from "+RoleMenu.TABLE_NAME+" where role_id=?",roleId);
		List<String> menuids=new LinkedList<String>();
		for(RoleMenu m:roleMenus) {
			menuids.add(m.getMenuId());
		}
		return menuids;
	}

	@Override
	public boolean updateRoleMenus(String roleId, List<String> menuIds) {
		if(menuIds.isEmpty()) {
			Db.delete("delete from "+RoleMenu.TABLE_NAME+" where role_id=? ",roleId);
			return true;
		}
		
		StringBuffer sb=new StringBuffer();
		for(String id:menuIds) {
			if(!StrKit.isBlank(id)) {
				if(RoleMenu.dao.findByIds(roleId,id)==null) {
					RoleMenu roleMenu=new RoleMenu();
					roleMenu.setRoleId(roleId);
					roleMenu.setMenuId(id);
					roleMenu.save();
				}
				sb.append("'").append(id).append("',");
			}
		}
		if(!StrKit.isBlank(sb.toString())) {
			Db.delete("delete from "+RoleMenu.TABLE_NAME+" where role_id=? and menu_id not in ("+sb.substring(0,sb.length()-1)+")  ",roleId);
		}
        return true;
	}
	
    /**
     * 角色下拉列表
     *
     * @return
     */
	@Override
    public List<Role> listRoleOptions() {
        List<Role> options = Role.dao.find("select * from "+Role.TABLE_NAME+"  order by sort asc");
		return options;
    }


}
